import base64
import os

from config.config import get_upload_dir_path
from datetime import datetime

from tools.Func import get_random_str


def get_random_filename(suffix:str) -> str:

  path= get_upload_dir_path()+ datetime.now().strftime('%Y/%m/%d')+get_random_str()+"."+suffix

  os.makedirs(os.path.dirname(path), exist_ok=True)
  return path

def base64str_to_image(base64_str, output_path=None):
    # 处理带MIME头的Base64字符串
    if ';' in base64_str and ',' in base64_str:
        header, data = base64_str.split(',', 1)
    else:
        data = base64_str

        # Base64解码
    img_data = base64.b64decode(data)

    # 确定输出路径和格式
    if output_path is None:
        if ';' in base64_str:
            # 从MIME头提取图片类型
            mime_type = header.split(';')[0].split('/')[1]
        else:
            mime_type = 'png'  # 默认格式
        output_path = f'decoded_image.{mime_type}'

        # 写入图片文件
    with open(output_path, 'wb') as f:
        f.write(img_data)

    return output_path


# 示例使用
if __name__ == '__main__':
    # 示例Base64字符串（实际使用时应替换为真实数据）
    example_base64 = "";

    # 转换并保存图片
    output_file = base64_to_image(example_base64)
    print(f'图片已成功保存至：{output_file}')
